import { v4 as uuidv4 } from 'uuid';

export default {
  use(app, knex){

    //新增ip
    app.post('/ip/add', function(req, res){
      knex('ip')
      .where('ip', '=', req.body.ip)
      .then(rows => {
        if(rows.length > 0){
          res.send({
            code: 1,
            message: 'ip地址重复请修改后重新提交',
          })
        }else{
          knex('ip')
          .insert({id: uuidv4(), ...req.body})
          .then(row=>{
            res.send({
              code: 0,
              message: '新增ip成功'
            })
          })
          .catch(err=>{
            console.log(err)
            res.send({
              code: 1,
              message: err
            })
          })  
        }
      })
    })

    //查询ip
    app.get('/ip', function(req, res){
      knex('ip')
      // .where({user_id: req.user_id})
      .limit(1)
      .select('*').then(rows=>{
        res.send({
          code: 0,
          data: rows[0]
        })
      })  
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })

    
    //删除ip
    app.post('/ip/del', function(req, res){
      knex('ip')
      .where('id', req.body.id)
      .del()
      .then(row => {
        res.send({
          code: 0,
          data: 'ip删除成功'
        })
      })
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })

    
    //更新ip
    app.post('/ip/update', function(req, res){
      const data = req.body;
      const id = data.id;
      delete data.id;
      knex('ip')
      .where('id', '=', id)
      .update({
        ...data
      })
      .then(row => {
        res.send({
          code: 0,
          data: '更新ip成功'
        })
      })
      .catch(err => {
        res.send({
          code: 1,
          message: err
        })
      })
    })
  }
}

